package com.daon.common;

import com.daon.exception.ParamException;
import com.daon.exception.EnterpriseException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 1daon
 * @EMAIL 532418116@qq.com
 * @Version 创建时间：2018/3/12 下午8:49
 * @Modified By 异常捕获
 */
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver{

    private static final Logger logger = LoggerFactory.getLogger(SpringExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String url = request.getRequestURL().toString();
        ModelAndView mv;
        String defaultMsg = "System error";

        // 这里我们要求项目中所有请求json数据，都使用.json结尾
        if (url.endsWith(".do")) {
            if(ex instanceof ParamException){
                ServerResponse result = ServerResponse.createByErrorMessage(ex.getMessage());
                mv = new ModelAndView("jsonView", result.toMap());
            }else{
                logger.error("unknown json exception, url:" + url, ex);
                ServerResponse result = ServerResponse.createByErrorMessage(defaultMsg);
                mv = new ModelAndView("jsonView", result.toMap());
            }
        }else if (url.endsWith(".page")){ // 这里我们要求项目中所有请求page页面，都使用.page结尾
            logger.error("unknown page exception, url:" + url, ex);
            ServerResponse result = ServerResponse.createByErrorMessage(defaultMsg);
            mv = new ModelAndView("exception", result.toMap());
        }else {
            logger.error("unknow exception, url:" + url, ex);
            ServerResponse result = ServerResponse.createByErrorMessage(defaultMsg);
            mv = new ModelAndView("jsonView", result.toMap());
        }

        return mv;
    }
}
